const debug = process.env.NODE_ENV !== "production";

const MUTATION_TYPES = {
  ORDERIMPORT: "ORDERIMPORT",
  ORDERIMPORTNAME: "ORDERIMPORTNAME",
  UPDATE_GETTER_FLAG: 'UPDATE_GETTER_FLAG'
};

const state = {
  importDatas: {},
  orderImportNames: {},
  updateGetterFlag: null
};

const getters = {
  getOrderImportData: (state, getters) => (userId) => {
    console.log('Should update getter ?', state.updateGetterFlag);
    if (state.updateGetterFlag) {
      // 强制触发计算属性的重新计算
      const updatedOrderImportData = getters.getOrderImportData(userId);
      return updatedOrderImportData;
    } else {
      return state.importDatas[userId] || [];
    }
  }
};

const mutations = {
  [MUTATION_TYPES.ORDERIMPORT] (state, { importData, userId }) {
    state.importDatas[userId] = importData || [];
  },
  [MUTATION_TYPES.ORDERIMPORTNAME] (state, { orderImportName, userId }) {
    state.orderImportNames[userId] = orderImportName || null;
  },
  // 新增的mutation，用于标记需要重新计算getter
  [MUTATION_TYPES.UPDATE_GETTER_FLAG] (state, flag) {
    state.updateGetterFlag = flag;
  }
};


const actions = {
  async update ({ commit }, filter = []) {
    commit(MUTATION_TYPES.ORDERIMPORT, filter);
  },
  async updatedOrderImportData ({ commit }, { userId, importData = [] }) {
    commit(MUTATION_TYPES.UPDATE_GETTER_FLAG, true);
    commit(MUTATION_TYPES.ORDERIMPORT, { importData, userId });
    commit(MUTATION_TYPES.UPDATE_GETTER_FLAG, false);
  },
};

export default {
  strict: debug,
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
